function getServiceUrl(options){
    /* Se nn viene indicato alcun servizio, la chiamata AJAX non viene eseguita */
    if (options.service == null || options.service == '') return null;

    var service = '/AdminApplication/' + options.service;

    var attr = '';
    if (options.params != null){
        $.each(options.params, function(key, value){
            attr += key + '=' + value + '&';
        });
        if (attr != ''){
            attr = attr.substring(0, attr.length-1);
            service = service + '?' + attr;
        }
    }
    //console.log(service);
    return service;
}

/*
 * Funzione che esegue la chiamata ajax.
 * Utilizza il metodo GET e si aspetta un XML.
 * Quando la chiamata ha successo, viene eseguita la funzione indicata.
 * Se la chiamata riceve un errore, viene mostrato un popup.
 */
function ajaxRequest(options){
    
    var service = getServiceUrl(options);
    if (service == null) return;

    $.ajax({
        url: service,
        type: 'get',
        contentType: 'text/xml; charset="utf-8"',
        success: options.success,
        complete: function(data){
            //Controlla se il server ha restituito un errore
            var error = $(data).find('error').find('message').text();
            var cause = $(data).find('error').find('cause').text();
            if (cause != "") cause = ": " + cause;
            if (error != "") alert(error + cause);
        },
        error: function(){
            alert("Errore nella risposta dal server per il servizio: " + options.service);
        },
        timeout: 8000
    });
}

/*
* Funzione che esegue la chiamata ajax.
* Utilizza il metodo GET e si aspetta un HTML.
* Quando la chiamata ha successo, viene eseguita la funzione indicata.
* Se la chiamata riceve un errore, viene mostrato un popup.
*/
function ajaxRequestHTML(options){

    var service = getServiceUrl(options);
    if (service == null) return;

    $.ajax({
        url: service,
        type: 'get',
        contentType: 'text/html; charset="utf-8"',
        success: options.success,
        error: function(){
            alert("Errore nella risposta dal server per il servizio: " + service);
        },
        timeout: 8000
    });
}

/*
*Funzione che applica agli elementi dell'array elements l'azione fade scelta (in/out)
*/
function fade(action, elements){
    if (action == 'in'){
        $(elements).each(function(index, el){
            $(el).fadeIn('def', function(){});
        });
    } else if (action == 'out'){
        $(elements).each(function(index, el){
            $(el).fadeOut('def', function(){});
        });
    }
}

/*
*Funzione che converte la data timestamp in un formato leggibile.
*Restituisce un array [data, orario] con i seguenti formati:
*<ul>
*<li><strong>data:</strong> gg/mm/aaaa</li>
*<li><strong>orario:</strong> hh:mm:ss</li>
*/
function timestampToDate(timestamp){
    var dateTemp = new Date();
    dateTemp.setTime(timestamp + "000");
    var date = dateTemp.getDate() + "/" + (dateTemp.getMonth()+1) + "/" + dateTemp.getFullYear();
    var time = dateTemp.getHours() + ":" + dateTemp.getMinutes() + ":" + dateTemp.getSeconds();
    return [date, time]
}

function dateToTimestamp(date){
    var timestamp = Date.parse(date);
    return timestamp;
}

function loadNodes(array){
    //Funzione chiamata per il successo della richiesta ajax
    function success(data){
        $(array).each(function(index, obj){
            $(obj).find('option').remove();
            $(data).find('node').each(function(){
                $(obj).append('<option value="' + $(this).find('id').text() + '">Nodo ' + $(this).find('id').text() + '</option>');
            });
            $(obj).change();
        });
    }

    ajaxRequest({
        service: 'node',
        params: {},
        success: success
    });

}

function loadSensors(container, idNode){
    function success(data){
        $(container).find('option').remove();
        $(data).find('sensor').each(function(){
            $(container).append('<option value="' + $(this).find('node').text() + '">' + $(this).find('name').text() + '</option>');
        })
        $(container).change();
    }

    ajaxRequest({
        service: 'sensor',
        params: {
            action: 'find',
            idNodo: idNode
        },
        success: success
    });

}

function loadNodeInfo(idNodo){
    function success(data){
        var alias = $(data).find('alias').text();
        var corde = $(data).find('coorde').text();
        var cordn = $(data).find('coordn').text();
        $('#node #info').html("<b>Alias:</b> " + alias + "<br /><b>Coord E:</b> " + corde + "<br /><b>Coord N:</b> " + cordn);

    }
    
    ajaxRequest({
        service: 'node',
        params: {
            action: 'find',
            idNodo: idNodo
        },
        success: success
    });
}

function loadSensorInfo(idNodo, idSensore){
    function success(data){
        var corde = $(data).find('coorde').text();
        var cordn = $(data).find('coordn').text();
        var tipo = $(data).find('tiposensore').text();
        $('#sensor #info').html("<b>Coord E:</b> " + corde + "<br /><b>Coord N:</b> " + cordn + "<br /><b>Tipo:</b> " + tipo);
    }

    ajaxRequest({
        service: 'sensor',
        params: {
            action: 'find',
            idNodo: idNodo,
            idSensore: idSensore
        },
        success: success
    });

}

function printValues(data){
    var thead = "";
    var tbody = "";

    /*
     *  Variabili usate per tutti i tipi di sensore
     */
    var date;
    var time;
    var type = $(data).find('type').text();
    if(type == "attitude"){
        thead = "<thead><tr><th>Date</th><th>Time</th><th>AttitudeX</th><th>AttitudeY</th><th>AttitudeZ</th></tr></thead>";
        var attitudeX;
        var attitudeY;
        var attitudeZ;
        $(data).find('value').each(function(){
            [date, time] = timestampToDate($(this).find('timestamp').text());
            attitudeX = $(this).find('attitudeX').text();
            attitudeY = $(this).find('attitudeY').text();
            attitudeZ = $(this).find('attitudeZ').text();

            tbody += "<tr>"
            + "<td>" + date + "</td>"
            + "<td>" + time + "</td>"
            + "<td>" + attitudeX + "</td>"
            + "<td>" + attitudeY + "</td>"
            + "<td>" + attitudeZ + "</td>"
            + "</tr>";
        });
    }
    else if(type == "temperature"){
        thead = "<thead><tr><th>Date</th><th>Time</th><th>Valore</th></tr></thead>";
        var value;
        $(data).find('value').each(function(){
            [date, time] = timestampToDate($(this).find('timestamp').text());
            value = $(this).find('valore').text();

            tbody += "<tr><td>"+date+"</td><td>"+time+"</td><td>"+value+"</td></tr>\n";
        });
    }
    else if(type == "geophone"){
        thead =  "<thead><tr><th>Date</th><th>Time</th><th>MagnitudeX</th><th>MagnitudeY</th><th>MagnitudeZ</th><th>PeakX</th><th>PeakY</th><th>Peakz</th><th>NoiseX</th><th>NoiseY</th><th>NoiseZ</th></tr></thead>";
        $(data).find('value').each(function(){
            [date, time] = timestampToDate($(this).find('timestamp').text());
            var magnitudeX = $(this).find('magnitudeX').text();
            var magnitudeY = $(this).find('magnitudeY').text();
            var magnitudeZ = $(this).find('magnitudeZ').text();
            var peakX = $(this).find('peakX').text();
            var peakY = $(this).find('peakY').text();
            var peakZ = $(this).find('peakZ').text();
            var noiseX = $(this).find('noiseX').text();
            var noiseY = $(this).find('noiseY').text();
            var noiseZ = $(this).find('noiseZ').text();

            tbody += "<tr><td>"+date+"</td><td>"+time+"</td><td>"+magnitudeX+"</td><td>"+magnitudeY+"</td><td>"+magnitudeZ+"</td><td>"+peakX+"</td><td>"+peakY+"</td><td>"+peakZ+"</td><td>"+noiseX+"</td><td>"+noiseY+"</td><td>"+noiseZ+"</td></tr>\n";
        });
    }
    else if(type == "crackmeter"){
        thead = "<thead><tr><th>Date</th><th>Time</th><th>Value</th></tr></thead>";
        $(data).find('value').each(function(){
            [date, time] = timestampToDate($(this).find('timestamp').text());
            var value = $(this).find('valore').text();
            tbody += "<tr><td>"+date+"</td><td>"+time+"</td><td>"+value+"</td></tr>\n";
        });
    }
    $('#values-table').find('tr').remove();
    $('#values-table').append('<thead>' + thead + '</thead><tbody>' + tbody + '</thead>');
}

/*funzione che carica i valori del sensore "idSensor" dato l'intervallo di tempo da "from" a "to" */
function loadValuesByDate(idNodo,idSensore,from,to){
    var fromA = from.split("/");
    var toA = to.split("/");
    var fromT = Date.parse(fromA[1] + '/' + fromA[0] + '/' + fromA[2])/1000;
    var toT = Date.parse(toA[1] + '/' + toA[0] + '/' + toA[2])/1000;
   
    ajaxRequest({
        service: 'value',
        params: {
            filter: 'date',
            idNodo: idNodo,
            idSensore: idSensore,
            from: fromT,
            to: toT
        },
        success: printValues
    });
}

/* funzione che carica gli ultimi n valori del sensore "idSensor"*/
function loadValues(idNodo,idSensore,max){
    ajaxRequest({
        service: 'value',
        params: {
            filter: 'limit',
            idNodo: idNodo,
            idSensore: idSensore,
            max: max
        },
        success: printValues
    });
}

/*function loadLastValues(){
    function success(data){
         
        var type = $(data).find('type').text();
        var i = "";
        var date;
        var time;
        
        if(type == "attitude"){
            i = "<thead><tr><th>Date</th><th>Time</th><th>AttitudeX</th><th>AttitudeY</th><th>AttitudeZ</th></tr></thead>";
            var attitudeX;
            var attitudeY;
            var attitudeZ;
            $(data).find('value').each(function(){
                $(data).find('timestamp').text().each(function(){
                   
                    [date, time] = timestampToDate(timestamp);
                    attitudeX = $(this).find('attitudeX').text();
                    attitudeY = $(this).find('attitudeY').text();
                    attitudeZ = $(this).find('attitudeZ').text();
                
                    i += "<tr>"
                    + "<td>" + date + "</td>"
                    + "<td>" + time + "</td>"
                    + "<td>" + attitudeX + "</td>"
                    + "<td>" + attitudeY + "</td>"
                    + "<td>" + attitudeZ + "</td>"
                    + "</tr>";
                
                })

            });
        }
         
    }
    
}*/

function loadRelations(){
    function success(data){
        $('#summary-table #list').find('tr').remove();
        if ($(data).find('relation').size() > 0) $('#summary #force-update').attr("disabled", "");
        else $('#summary #force-update').attr("disabled", "disabled");
        $(data).find('relation').each(function(){
            var content = '<tr id="relation-' + $(this).find('idSensoreGis').text() + '">'
            + '<td>' + $(this).find('labelSensoreGis').text() + '</td>'
            + '<td>' + $(this).find('idNodoPerla').text() + '</td>'
            + '<td>' + $(this).find('idSensoreGis').text() + '</td>'
            + '<td>' + $(this).find('notifica').text() + '</td>'
            + '<td>'
            + '<button id="edit" value="' + $(this).find('idSensoreGis').text() + '"><span class="icon"></span><span class=\"text\">Cambia notifica</span></button><button id="delete" value="' + $(this).find('idSensoreGis').text() + '"><span class="icon"></span><span class=\"text\">Cancella</span></button>'
            + '</td>'
            + '</tr>';
        
            $('#summary-table #list').append(content);
            $('#relation-' + $(this).find('idSensoreGis').text() + ' #delete').click(function(){
                removeRelation($(this).val());
                return false;
            });
            $('#relation-' + $(this).find('idSensoreGis').text() + ' #edit').click(function(){
                changeRelation($(this).val());
                return false;
            });
        });
    }

    ajaxRequest({
        service: 'relation',
        params: {},
        success: success
    });
}

function createRelation(){
    ajaxRequest({
        service: 'relation',
        params: {
            action: 'create',
            idNodo: $('#new #nodes option:selected').val(),
            nome: $('#new #label').val(),
            notifica: $('#new #notify').attr('checked')
        },
        success: loadRelations
    });
}

function removeRelation(idGis){
    ajaxRequest({
        service: 'relation',
        params: {
            action: 'remove',
            idSensore: idGis
        },
        success: loadRelations
    });
}

function changeRelation(idGis){
    ajaxRequest({
        service: 'relation',
        params: {
            action: 'change',
            idSensore: idGis
        },
        success: loadRelations
    });
}

/* funzione che carica le informazioni di tutti i nodi presenti in Perla*/
function allNodes(){
    function success(data){
        $('#extra-infos-wrapper #body').html(data);
        fade('in', ['#extra-infos-wrapper', '#extra-infos-background']);
    }
    ajaxRequestHTML({
        service: 'extra',
        params: {
            what: 'nodes'
        },
        success: success
    });
     
}
/* funzione che carica le informazioni di tutti i sensori presenti in Perla*/
function allSensors(){
    function success(data){
        $('#extra-infos-wrapper #body').html(data);
        fade('in', ['#extra-infos-wrapper', '#extra-infos-background']);
    }
    ajaxRequestHTML({
        service: 'extra',
        params: {
            what: 'sensors'
        },
        success: success
    });
}

function updateAll(){
    function success(){
        alert('Aggiornamento avvenuto con successo.');
    }
    ajaxRequest({
        service: 'update',
        params: {},
        success: success
    });
}